﻿using CodeBuilder.Core.Domain.Models;
using CodeBuilder.Core.Features.Tables;

using MediatR;

using Tszy.CodeBuilder.Features.Builders;

namespace Tszy.CodeBuilder.Features;

public class CodeExecutor
{
    private readonly IMediator _mediator;

    public CodeExecutor(IMediator mediator)
    {
        _mediator = mediator;
    }

    public async Task Execute(string databaseName, string tableName, string basenamespace = "Zhimi.Domain")
    {
        var tables = await GetTablesAsync(databaseName, tableName);

        foreach (var table in tables)
        {
            var model = ModelClassBuilder.Execute(table, basenamespace);
            IRepositoryClassBuilder.InterfaceExecute(table, model, basenamespace);
            IRepositoryClassBuilder.ClassExecute(table, model, basenamespace);

            Console.WriteLine($"{model} 表模型生成完成！");
        }
    }

    private async Task<IEnumerable<CodeTable>> GetTablesAsync(string databaseName, string tableName)
    {
        var tables = await _mediator.Send(new GetTable.Request(databaseName, tableName));

        if (!tables.Status)
            return Enumerable.Empty<CodeTable>();

        return tables.Data?.Tables ?? Enumerable.Empty<CodeTable>();
    }
}